<template>
  <div>
    <el-row class="topRow" type="flex">
      <!-- PENDING -->
      <template v-if="pageName === 'PENDING'">
        <el-button
          type="primary"
          @click="orderConfirm('more')"
        >Confirm</el-button>
        <el-button
          type="primary"
          :disabled="false"
          @click="showMoveDialog('more', '')"
        >Fulfill By Self</el-button>
        <el-button type="primary" @click="importOrder">Import</el-button>
      </template>
      <!-- CONFIRM -->
      <template v-if="pageName === 'CONFIRM'">
        <el-button
          type="success"
          @click="showChannelDialog('more', '', 'submit')"
        >Online Fulfill</el-button>

        <el-button
          v-preventReClick
          type="primary"
          @click="orderGoBack('more')"
        >Return</el-button>
      </template>
      <!-- PROCESSING -->
      <template v-if="pageName === 'PROCESSING'">
        <el-button
          v-preventReClick
          type="primary"
          @click="orderUrgent('more')"
        >Urgent</el-button>
        <el-button
          type="primary"
          @click="showChannelDialog('more', '', 'change')"
        >Change Carrier</el-button>
        <el-button
          type="primary"
          @click="showAppealDialog('more')"
        >Cancel</el-button>
      </template>
      <!-- PACKING -->
      <template v-if="pageName === 'PACKING'">
        <el-button
          type="primary"
          @click="importTracking"
        >Import Tracking</el-button>
        <el-button
          type="primary"
          @click="showChannelDialog('more', '', 'change', true)"
        >Change Carrier</el-button>
      </template>
      <!-- UNSHIPPED -->
      <template v-if="pageName === 'UNSHIPPED'">
        <el-button v-preventReClick type="primary">Return Tracking</el-button>
        <el-button
          type="primary"
          @click="showChannelDialog('more', '', 'change')"
        >Change Carrier</el-button>
      </template>
      <!-- SHIPPED -->
      <template v-if="pageName === 'SHIPPED'">
        <el-button v-preventReClick type="primary" @click="applyLabel('more')">Download Shipping Lable</el-button>
        <!-- <el-tooltip content="根据（productName variantTitle，Sku关键字匹配）" placement="top" effect="light">
          <el-button v-preventReClick type="primary" @click="applyLabel('more')">Download Shipping Lable<i class="el-icon-info el-icon--right" /></el-button>
        </el-tooltip> -->
        <!-- <el-button type="primary">Reship</el-button> -->
      </template>
      <!-- TRASH -->
      <template v-if="pageName === 'TRASH'">
        <el-button
          type="primary"
          @click="orderDelete('more')"
        >Delete</el-button>
        <el-button
          v-preventReClick
          type="primary"
          @click="orderRecover('more')"
        >Recover</el-button>
      </template>
      <el-dropdown id="beihuo" trigger="click" @command="handleCommand">
        <el-button
          type="primary"
        >Export<i
          class="el-icon-arrow-down el-icon--right"
        /></el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="1">Select the export</el-dropdown-item>
          <el-dropdown-item command="2">All export</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button
        v-if="pageName === 'PENDING' || pageName === 'CONFIRM'"
        v-preventReClick
        type="primary"
        :disabled="false"
        @click="orderTrash('more')"
      >Delete</el-button>
      <el-button type="primary" @click="showNoteDialog('more')">Note</el-button>
      <el-popover class="sortPop" width="260">
        <div v-for="(sortObj, index) in sortList" :key="index">
          <el-row style="margin-bottom:4px;">
            <el-col :span="14" style="padding-top:4px;">
              {{ sortObj.name }}
            </el-col>
            <el-col :span="10">
              <el-button
                size="mini"
                :class="[
                  activeSort[0] === index && activeSort[1] === 0 ? 'active' : '',
                  'sortBtn'
                ]"
                @click="addSort('asc', sortObj.value, index, 0)"
              >
                <svg-icon icon-class="asc" />
              </el-button>
              <el-button
                size="mini"
                :class="[
                  activeSort[0] === index && activeSort[1] === 1 ? 'active' : '',
                  'sortBtn'
                ]"
                @click="addSort('desc', sortObj.value, index, 1)"
              >
                <svg-icon icon-class="desc" />
              </el-button>
            </el-col>
          </el-row>
        </div>
        <el-button id="sort" slot="reference" :class="[activeSort.length > 0 ? 'active' : '', 'sortClickBtn']">
          <i class="el-icon-d-caret" />
          sort
          <i class="el-icon-caret-bottom" />
        </el-button>
      </el-popover>
    </el-row>

    <!-- 导入订单弹窗-->
    <el-dialog
      append-to-body
      title="Import Order"
      :visible.sync="dialogImport"
      width="450px"
      @close="closeOrderImport"
    >
      <el-form ref="importForm" :disabled="orderUploading">
        <el-form-item>
          <el-select
            v-model="importantStoreId"
            placeholder="select store"
            @visible-change="getStoreList"
          >
            <el-option
              v-for="item in storeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            v-preventReClick
            type="text"
            @click="downOrderTemplate()"
          >Template Download</el-button>
          <el-upload
            action=""
            accept=".xlsx,.xls,.cvs"
            :http-request="uploadFile"
            :show-file-list="false"
            style="margin: 10px 0;"
          >
            <el-button v-preventReClick type="primary">Upload</el-button>
          </el-upload>
          <div v-if="!uploadedFile">Selected: <span>No File</span></div>
          <div v-else>
            Selected: <span style="color: #67c23a">{{ uploadedFile }}</span>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeOrderImport">Close</el-button>
        <el-button
          v-preventReClick
          type="primary"
          :loading="orderUploading"
          @click="orderUpload"
        >Confirm</el-button>
      </div>
    </el-dialog>

    <!-- 导入运单号弹窗-->
    <el-dialog
      append-to-body
      title="Import Tracking"
      :visible.sync="trackingVisible"
      width="450px"
      @close="closeTrackingImport"
    >
      <el-form ref="importForm" :disabled="trackingUploading">
        <el-form-item label="" prop="path">
          <el-button
            v-preventReClick
            type="text"
            @click="downTrackingTemplate"
          >Template Download</el-button>
          <el-upload
            action=""
            accept=".xlsx,.xls"
            :http-request="uploadFile"
            :show-file-list="false"
            style="margin: 10px 0;"
          >
            <el-button v-preventReClick type="primary">Upload</el-button>
          </el-upload>
          <div v-if="!uploadedFile">Selected: <span>No File</span></div>
          <div v-else>
            Selected: <span style="color: #67c23a">{{ uploadedFile }}</span>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeTrackingImport">Close</el-button>
        <el-button
          v-preventReClick
          type="primary"
          :loading="trackingUploading"
          @click="trackingUpload"
        >Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  downOrderTemplate,
  downTrackingTemplate,
  orderUpload,
  trackingUpload
} from '@/api/store';
import { authorizedList } from '@/api/authorized';
export default {
  props: {
    pageName: {
      type: String,
      required: true
    },
    searchParams: {
      type: Object,
      default: () => ({})
    },
    fatherInit: {
      type: Function,
      required: true
    },
    orderConfirm: {
      type: Function,
      required: true
    },
    orderGoBack: {
      type: Function,
      required: true
    },
    showChannelDialog: {
      type: Function,
      required: true
    },
    showMoveDialog: {
      type: Function,
      required: true
    },
    orderSubmit: {
      type: Function,
      required: true
    },
    orderUrgent: {
      type: Function,
      required: true
    },
    orderExport: {
      type: Function,
      required: true
    },
    applyLabel: {
      type: Function,
      required: true
    },
    showNoteDialog: {
      type: Function,
      required: true
    },
    showAppealDialog: {
      type: Function,
      required: true
    },
    orderTrash: {
      type: Function,
      required: true
    },
    orderPacking: {
      type: Function,
      required: true
    },
    orderRecover: {
      type: Function,
      required: true
    },
    orderDelete: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      sortList: [
        {
          visible: '',
          name: 'orderId',
          value: 'orderId'
        },
        {
          visible: '',
          name: 'sku',
          value: 'sku'
        },
        {
          visible: '',
          name: 'paymentDate',
          value: 'paymentDate'
        }
      ],
      activeSort: [],
      dialogImport: false,
      orderUploading: false,
      storeList: [],
      importantStoreId: null,
      orderFormData: null,
      uploadedFile: '',
      trackingVisible: false,
      trackingUploading: false
    };
  },
  methods: {
    addSort(type, val, index, i) {
      // sort排序
      this.activeSort = [index, i];
      this.searchParams['sortOrder'] = type;
      this.searchParams['sortField'] = val;
      this.fatherInit();
    },
    importOrder() {
      this.importantStoreId = null;
      this.orderFormData = null;
      this.uploadedFile = '';
      this.dialogImport = true;
    },
    closeOrderImport() {
      if (this.orderUploading) {
        this.$confirm(
          'The file is being imported. Do you want to continue closing the popover?',
          'Hint',
          {
            confirmButtonText: 'Yes',
            cancelButtonText: 'No',
            type: 'warning'
          }
        )
          .then(() => {
            this.dialogImport = false;
          })
          .catch(() => {
            return false;
          });
      } else {
        this.dialogImport = false;
      }
    },
    closeTrackingImport() {
      if (this.trackingUploading) {
        this.$confirm(
          'The file is being imported. Do you want to continue closing the popover?',
          'Hint',
          {
            confirmButtonText: 'Yes',
            cancelButtonText: 'No',
            type: 'warning'
          }
        )
          .then(() => {
            this.trackingVisible = false;
          })
          .catch(() => {
            return false;
          });
      } else {
        this.trackingVisible = false;
      }
    },
    importTracking() {
      this.orderFormData = null;
      this.uploadedFile = '';
      this.trackingVisible = true;
    },
    downOrderTemplate() {
      // 下载订单模板
      downOrderTemplate().then((res) => {
        this.downloadByBlob(res, this.$message);
      });
    },
    downTrackingTemplate() {
      downTrackingTemplate().then((res) => {
        this.downloadByBlob(res, this.$message);
      });
    },
    uploadFile(params) {
      this.orderFormData = new FormData();
      this.orderFormData.append('file', params.file);
      this.uploadedFile = params.file.name;
    },
    getStoreList(val) {
      // 选择店铺
      if (val) {
        authorizedList({ storeType: 'VIRTUAL' }).then((res) => {
          this.storeList = res.data;
        });
      }
    },
    orderUpload() {
      // 导入订单
      if (!this.importantStoreId) {
        return this.$message.warning('Please choose your store first.');
      }
      if (this.orderFormData === null) {
        return this.$message.warning('Please upload your order first.');
      }
      this.orderUploading = true;
      orderUpload(this.importantStoreId, this.orderFormData)
        .then((res) => {
          this.orderUploading = false;
          this.dialogImport = false;
          if (res.code === 200) {
            if (res.data.length > 0) {
              const orderNos = [];
              let tip = '';
              res.data.forEach((item) => {
                orderNos.push(item.orderNo);
                tip = item.note;
              });
              this.$message.warning({
                dangerouslyUseHTMLString: true,
                message: `
                <p>orderNo：${orderNos.join(', ')}。${tip}</p>
              `,
                duration: 15000,
                showClose: true
              });
            } else {
              this.$message.success('Import Success');
            }
            this.fatherInit();
          } else {
            this.$message.error(res.message);
          }
        })
        .catch(() => {
          this.orderUploading = false;
        });
    },
    trackingUpload() {
      if (this.orderFormData === null) {
        return this.$message.warning('Please upload your order first.');
      }
      this.trackingUploading = true;
      trackingUpload(this.orderFormData)
        .then((res) => {
          this.trackingUploading = false;
          if (res.code === 200) {
            this.trackingVisible = false;
            if (res.data.length > 0) {
              const orderNos = [];
              let tip = '';
              res.data.forEach((item) => {
                orderNos.push(item.orderNo);
                tip = item.note;
              });
              this.$message.warning({
                dangerouslyUseHTMLString: true,
                message: `
                <p>orderNo：${orderNos.join(', ')}。${tip}</p>
              `,
                duration: 15000,
                showClose: true
              });
            } else {
              this.$message.success('Import Success');
            }
            this.fatherInit();
          }
        })
        .catch(() => {
          this.trackingUploading = false;
        });
    },
    downloadByBlob(res, message) {
      // 下载blob数据
      if (JSON.stringify(res) !== '{}') {
        message.success('The file has been downloaded');
        const contentDisposition = res.headers['content-disposition'];
        if (
          contentDisposition.indexOf('fileName') >= 0 ||
          contentDisposition.indexOf('filename') >= 0
        ) {
          const filename =
            contentDisposition.split('fileName=')[1] ||
            contentDisposition.split('filename=')[1];
          const blob = new Blob([res.data]);
          const downloadElement = document.createElement('a');
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          downloadElement.href = href;
          downloadElement.download = filename; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放掉blob对象
        }
      } else {
        message.error(
          'An error occurred while downloading. No infomation available!!'
        );
      }
    },
    handleCommand(val) {
      // 导出  1:选中   2:全部
      if (!val) return;
      this.orderExport(val);
    }
  }
};
</script>
<style lang="scss" scoped>
.el-button {
  margin-right: 10px;
}
.el-button + .el-button {
  margin-left: 0;
}
.topRow {
  padding: 10px 0;
  background-color: #fff;
  border-bottom: 1px solid rgba(0, 21, 41, 0.08);
}
.sortBtn {
  margin-right: 0;
  &.active {
    border-color: #16AD61;
  }
}
.sortClickBtn {
  &.active {
    border-color: #16AD61;
  }
}
</style>
